package com.ltwc.lttv.activity

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.ltwc.lttv.R
import com.ltwc.lttv.Request
import com.ltwc.lttv.api.InfoMessage
import com.ltwc.lttv.listener.InfoDataCallBack
import com.ltwc.lttv.tools.GetDeviceId
import com.ltwc.lttv.tools.SP
import com.ltwc.lttv.tools.SaveDataTool
import com.ltwc.lttv.tools.Utils
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

/**
 * Description：
 * Created on 2024/2/1 20:07
 * Organization:华云
 * author：AHuangSHang
 **/
class StartActivity : FragmentActivity(), InfoDataCallBack {
    private var TMac: TextView? = null;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_start)
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        TMac = findViewById<TextView>(R.id.mac);
        //最后再次更新app的缓存
        this.let { Request.initInfoDataCallBack(it) }
        getDevicesID()
    }

    init {
        lifecycleScope.launch(Dispatchers.IO) {
            val utilsJob = async(start = CoroutineStart.LAZY) { Utils.init() }

            utilsJob.start()

//            utilsJob.await()
        }
    }

    private fun getDevicesID() {
        Thread {
            try {
                //获取保存在sd中的 设备唯一标识符
                val readDeviceID: String =
                    GetDeviceId.getDeviceId(this)
                TMac?.setText(readDeviceID);
                SP.deviceId = readDeviceID
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                Request.fetchDataInfo()
            }
        }.start()
    }

    override fun call(list: List<InfoMessage>) {
        SaveDataTool.saveListToPrefs(this, "main", list)
        val intent = Intent(this@StartActivity, MainActivity::class.java)
        startActivity(intent)
        finish()
    }

    override fun callError(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        if (SaveDataTool.getListFromPrefs(this, "main") != "") {
            //说明以前有保存到电视台信息，让进入播放，防止服务器挂了获取不到信息不能看
            val intent = Intent(this@StartActivity, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
    }
}